using System;
using Microsoft.Practices.Composite.Presentation.Regions;
using Microsoft.Practices.Composite.Regions;
using Microsoft.Practices.Unity;
using PrismNavigationFramework.Navigation.Controls;
using PrismNavigationFramework.RegionBehaviors;

namespace PrismNavigationFramework.RegionAdapters
{
    public class PrismMainFrameRegionAdapter : RegionAdapterBase<PrismNavigationMainFrame>
    {
        private readonly IUnityContainer _unityContainer;


        public PrismMainFrameRegionAdapter(IRegionBehaviorFactory regionBehaviorFactory, IUnityContainer unityContainer) : base(regionBehaviorFactory)
        {
            _unityContainer = unityContainer;
        }

        protected override void Adapt(IRegion region, PrismNavigationMainFrame regionTarget)
        {
            if (regionTarget == null)
            {
                throw new ArgumentNullException("regionTarget");
            }

            base.AttachBehaviors(region, regionTarget);

            if (!region.Behaviors.ContainsKey(PrismNavigationMainFrameRegionBehavior.BehaviorKey))
            {
                var behavior = this._unityContainer.Resolve<PrismNavigationMainFrameRegionBehavior>();
                behavior.HostFrame = regionTarget;
                region.Behaviors.Add(PrismNavigationMainFrameRegionBehavior.BehaviorKey, behavior);
            }            
        }

        protected override IRegion CreateRegion()
        {           
            return new SingleActiveRegion();
        }
    }

}